package com.example.duihua.service.impl;

import com.example.duihua.entity.User;
import com.example.duihua.mapper.UserMapper;
import com.example.duihua.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return userMapper.countByUsername(username) > 0;
    }
    
    @Override
    public User save(User user) {
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置创建时间和更新时间
        Date now = new Date();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        
        userMapper.insert(user);
        return user;
    }
    
    @Override
    public boolean updateStatus(Long userId, String status) {
        return userMapper.updateStatus(userId, status) > 0;
    }
    
    @Override
    public User updateProfile(User user) {
        // 设置更新时间
        user.setUpdatedAt(new Date());
        
        userMapper.updateProfile(user);
        return userMapper.findById(user.getId());
    }
    
    @Override
    public java.util.List<User> getAllUsers() {
        return userMapper.findAll();
    }
}
